package com.forte.fortePoiUtils.typeEnum;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.InputStream;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * Excel文件扩展名类型枚举
 */
public enum ExcelType {
    EXCEL_XLS(in -> {
        try {
            return new HSSFWorkbook(in);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }, HSSFWorkbook::new),
    EXCEL_XLSX(in -> {
        try {
            return new XSSFWorkbook(in);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }, XSSFWorkbook::new) ,
    EXCEL_2003(in -> {
        try {
            return new HSSFWorkbook(in);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }, HSSFWorkbook::new) ,
    EXCEL_2010(in -> {
        try {
            return new XSSFWorkbook(in);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }, XSSFWorkbook::new) ,
    XSSF(in -> {
        try {
            return new XSSFWorkbook(in);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }, XSSFWorkbook::new),
    HSSF(in -> {
        try {
            return new HSSFWorkbook(in);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }, HSSFWorkbook::new);

    /** 工作簿获取函数 */
    private final Function<InputStream, Workbook> workbookReader;
    private final Supplier<Workbook> workbookGetter;

    ExcelType(Function<InputStream, Workbook> workBookGetter, Supplier<Workbook> workbookGetter){
        this.workbookReader = workBookGetter;
        this.workbookGetter = workbookGetter;
    }

    public Function<InputStream, Workbook> reader(){
        return workbookReader;
    }
    public Supplier<Workbook> getter(){
        return workbookGetter;
    }

    public Workbook getWorkbook(){
        return workbookGetter.get();
    }

    public Workbook getWorkbook(InputStream in, boolean close){
        Workbook book = workbookReader.apply(in);
        if(close){
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return book;
    }

    public Workbook getWorkbook(InputStream in){
        return getWorkbook(in, true);
    }
}
